﻿#nullable enable

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using PHMEE.EntityFrameworkCore;

namespace PHMEE.EnergyEfficiency;

public class CiiReductionFactorRepository : ICiiReductionFactorRepository
{
    private readonly PHMEEDbContext _context;

    public CiiReductionFactorRepository(PHMEEDbContext context)
    {
        _context = context;
    }

    public Task<CiiReductionFactor?> GetByYearAsync(int year)
    {
        return _context.CiiReductionFactors
            .FirstOrDefaultAsync(c => c.Year == year);
    }

    public Task<List<CiiReductionFactor>> GetAllAsync()
    {
        return _context.CiiReductionFactors.ToListAsync();
    }

    public async Task InsertAsync(CiiReductionFactor ciiReductionFactor)
    {
        await _context.CiiReductionFactors.AddAsync(ciiReductionFactor);
        await _context.SaveChangesAsync();
    }
    
    public async Task InsertManyAsync(IEnumerable<CiiReductionFactor> ciiReductionFactors)
    {
        await _context.CiiReductionFactors.AddRangeAsync(ciiReductionFactors);
        await _context.SaveChangesAsync();
    }

    public async Task UpdateAsync(CiiReductionFactor ciiReductionFactor)
    {
        _context.CiiReductionFactors.Update(ciiReductionFactor);
        await _context.SaveChangesAsync();
    }

    public async Task DeleteByYearAsync(int year)
    {
        var factor = await _context.CiiReductionFactors.FirstOrDefaultAsync(c => c.Year == year);
        if (factor != null)
        {
            _context.CiiReductionFactors.Remove(factor);
            await _context.SaveChangesAsync();
        }
    }
}